package cn.iocoder.yudao.module.product.controller.admin.report;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.product.controller.admin.report.vo.ReportDownloadExportReqVO;
import cn.iocoder.yudao.module.product.controller.admin.report.vo.ReportDownloadReqVO;
import cn.iocoder.yudao.module.product.controller.admin.report.vo.ReportDownloadRespVO;
import cn.iocoder.yudao.module.product.controller.admin.report.vo.ReportExportReqVO;
import cn.iocoder.yudao.module.product.dal.mysql.report.ReportDownloadMapper;
import cn.iocoder.yudao.module.product.util.TranslateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.REPORT_LANGUAGE_NOT_EXISTS;

import cn.iocoder.yudao.module.product.dal.dataobject.report.ReportDownloadDO;
import cn.iocoder.yudao.module.product.convert.report.ReportDownloadConvert;
import cn.iocoder.yudao.module.product.service.report.ReportDownloadService;

import java.io.IOException;

@Tag(name = "管理后台 - 报告下载")
@RestController
@RequestMapping("/product/report-download")
@Validated
public class ReportDownloadController {

    @Resource
    private ReportDownloadMapper reportDownloadMapper;

    @Resource
    private ReportDownloadService reportDownloadService;

    @PostMapping("/create")
    @Operation(summary = "创建报告下载")
    @PreAuthorize("@ss.hasPermission('product:report-download:create')")
    public CommonResult<String> createReportDownload(@Valid @RequestBody ReportDownloadExportReqVO reqVO) throws IOException, InterruptedException {
        Long downloadId = reportDownloadService.createReportDownload(reqVO);
        // 选择语言
        Integer language = reqVO.getType();
        ReportDownloadDO reportDownload = reportDownloadMapper.selectById(downloadId);
        // 生成报告
        String fromLang = "zh";
        String toLang;
        String extend = "docx";
        String filePath = reportDownload.getReportUrl();
        String output = "docx";

        // 解析URL，获取文件名
        String[] urlSplit = reportDownload.getReportUrl().split("/");
        String fileName = urlSplit[urlSplit.length - 1];
        System.out.println(fileName);

        if (language == 1) {
            return success(reportDownload.getReportUrl());
        } else if (language == 2) {
            toLang = "en";
            fileName += "（英文版）";
        } else if (language == 3) {
            toLang = "kor";
            fileName += "（韩文版）";
        } else {
            throw exception(REPORT_LANGUAGE_NOT_EXISTS);
        }

        TranslateUtil translate = new TranslateUtil("20230625001723471", "tAUvXp7Op0HpmrDDUONo");
        // 创建报价服务
        String quoteRet = translate.createQuoteJob(fromLang, toLang, extend, fileName, filePath);
        System.out.println("baojia");
        System.out.println(quoteRet);
        JSONObject quoteRetJson = JSON.parseObject(quoteRet);
        String fileId = quoteRetJson.getJSONObject("data").getString("fileId");

        // 查询报价结果
        String queryQuoteRet = translate.queryQuote(fileId);
        System.out.println("jiegou");
        System.out.println(queryQuoteRet);

        // 创建翻译服务
        String transRet = translate.createTransJob(fromLang, toLang, extend, fileName, filePath, output);
        System.out.println(transRet);
        JSONObject transRetJson = JSON.parseObject(transRet);
        String requestId = transRetJson.getJSONObject("data").getString("requestId");

        // 睡眠5秒
        Thread.sleep(5000);

        // 查询翻译结果
        String queryTransRet = translate.queryTrans(requestId);
        System.out.println(queryTransRet);
        JSONObject queryTransRetJson = JSON.parseObject(queryTransRet);
        System.out.println("finally");
        System.out.println(queryTransRetJson);
        return success(queryTransRetJson.getJSONObject("data").getString("fileSrcUrl"));
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除报告下载")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('product:report-download:delete')")
    public CommonResult<Boolean> deleteReportDownload(@RequestParam("id") Long id) {
        reportDownloadService.deleteReportDownload(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得报告下载")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('product:report-download:query')")
    public CommonResult<ReportDownloadRespVO> getReportDownload(@RequestParam("id") Long id) {
        ReportDownloadDO reportDownload = reportDownloadService.getReportDownload(id);
        return success(ReportDownloadConvert.INSTANCE.convert(reportDownload));
    }

    @PostMapping("/export")
    @Operation(summary = "导出核算报告")
    @PreAuthorize("@ss.hasPermission('product:report-download:export')")
    public CommonResult<String> exportReportDownload(@Valid @RequestBody ReportDownloadReqVO exportReqVO) throws IOException, InterruptedException {
        String result = reportDownloadService.exportReportDownload(exportReqVO);
        return success(result);
    }

}
